Ext.onReady(function(){
    Ext.define('SysUserModel',{
        extend: 'Ext.data.Model',
        fields: [
			 {name:'id',type:'string'},
             {name:'login_name',type:'string'},
             {name:'login_last',type:'date'},
             {name:'login_state',type:'string'},
             {name:'role__id',type:'string'},
             {name:'role__role_name',type:'string'},
             {name:'create_time',type:'string'},
             {name:'mac',type:'string'},
             {name:'ip',type:'string'},
             {name:'employe__id',type:'string'},
             {name:'employe__name',type:'string'}
        ]
    });
    //创建数据源
    var SysUserStore = Ext.create('Ext.data.Store', {
    	pageSize:20,
        model: 'SysUserModel',
	    proxy: {
	        type: 'ajax',
	        url: '/usercontrol/sysuser_list/',
	        actionMethods:'post',
	        reader: {
	            type: 'json',
	            root: 'rows',
	            totalProperty: 'totalCount'
	        }
	    },
	    autoLoad: true
    });  

    //创建Grid
    var SysUserGrid = Ext.create('Ext.grid.Panel',{
        store: SysUserStore,
        //selModel:Ext.create('Ext.selection.CheckboxModel'),
        loadMask:true,
        columnLines:true,
        columns: [
            Ext.create('Ext.grid.RowNumberer'),// 序列
            {text: "用户名", width: 80, dataIndex: 'login_name', sortable: false},
            {text: "当前状态", width: 60, dataIndex: 'login_state', sortable: false,
            	renderer: function(value){
            		if (value==1)
            			return "有效";
            		else
            			return "失效";
            	}
            },
            {text: "创建时间", width: 140, dataIndex: 'create_time', sortable: false},
            {text: "最近登录时间", width: 140, dataIndex: 'login_last', sortable: false},             
            {text: "权限角色", width: 80, dataIndex: 'role__role_name', sortable: false},
            {text: "关联员工", width: 80, dataIndex: 'employe__name', sortable: false},
            {text: "MAC地址", width: 100, dataIndex: 'mac', sortable: false,hidden : true},
            {text: "IP地址", width: 100, dataIndex: 'ip', sortable: false,hidden : true}
        ],
        viewConfig: {
            stripeRows: true,
            listeners: {
                itemclick: function(dataview, record, item, index, e) {
    				
                },
                itemdblclick: function(dataview, record, item, index, e) {
                	var selected = SysUserGrid.getSelectionModel().getSelection();
        			if(selected!=''){
	        			form.getForm().findField('login_pwd').setDisabled(true);
	        			form.getForm().reset();
						form.loadRecord(selected[0]);
	        			win.show();
	    			}else{
	    				Ext.Msg.alert('系统提示', '请选择需要修改的账号!');
	    			}
                }
            }
        },
        dockedItems : [{
            xtype : 'pagingtoolbar',
            store : SysUserStore,
            dock : 'bottom',
            displayInfo : true,
            autoScroll:true 
        },{
        	dock:'top',
        	xtype:'toolbar',
        	items:[{
        		id:'login_name',
        		name:'login_name',
        		xtype:'textfield',
        		labelWidth: 50,
            	width: 160,
        		fieldLabel:'用户名'
        	},{
        		xtype:'button',
        		text:'查询',
        		iconCls:'search', 
        		handler:function(){
        			var params = { login_name: Ext.getCmp('login_name').getValue() };
        		    Ext.apply(SysUserStore.proxy.extraParams, params);
        		    SysUserStore.currentPage=1;
        		    SysUserStore.load();
        		}
        	},{
        		xtype:'button',
        		text:'添加',
        		iconCls:'add', 
        		handler:function(){
        			form.getForm().findField('login_pwd').setDisabled(false);
        			form.getForm().reset();
        			win.show();
        		}
        	},{
        		xtype:'button',
        		text:'修改',
        		iconCls:'edit',
        		handler:function(){
        			var selected = SysUserGrid.getSelectionModel().getSelection();
        			if(selected!=''){
	        			form.getForm().findField('login_pwd').setDisabled(true);
	        			form.getForm().reset();
						form.loadRecord(selected[0]);
	        			win.show();
	    			}else{
	    				Ext.Msg.alert('系统提示', '请选择需要修改的账号!');
	    			}	        			
        		}
        	},{
        		xtype:'button',
        		text:'删除',
        		iconCls:'delete',
        		handler:function(){
        			var selected = SysUserGrid.getSelectionModel().getSelection();
        			if(selected !=''){
	        			Ext.MessageBox.confirm('提示', '确认删除吗?', function(btn){
	        				if(btn=='yes'){
			        			var ids=[];
			        			Ext.each(selected, function (item) {
			        				ids.push(item.data.id);
			        			});
			        			Ext.Ajax.request({
			        			    url:'/usercontrol/sysuser_del/',
			        			    method : 'post',
			        			    params:{
			        			    	ids:ids.join(",")
			        			    },
			        			    success:function(response){
			        			        var results =  Ext.decode(response.responseText);
			        			        if(results.success){
			        			        	SysUserStore.load();
			        			        }else{
			        			        	Ext.Msg.alert('系统提示', results.message);
			        			        }
			        			    }
			        			});
	        				}
	        			});
        			}else{
        				Ext.Msg.alert('系统提示', '请选择需要删除的账号!');
        			}        			
        			
        		}
        	},{
        		xtype:'button',
        		text:'重置密码',
        		iconCls:'edit',
        		handler:function(){
        			var selected = SysUserGrid.getSelectionModel().getSelection();
        			if(selected!=''){
        				var id=''
        				Ext.each(selected, function (item) {
	        				id=item.data.id;
	        			});
	        			Ext.Ajax.request({
	        			    url:'/usercontrol/sysuser_pwd_reset/',
	        			    method : 'post',
	        			    params:{ id:id },
	        			    success:function(response){
	        			        var results =  Ext.decode(response.responseText);
	        			        if(results.success){
	        			        	SysUserStore.load();
	        			        	Ext.Msg.alert('系统提示', '重置密码成功!');
	        			        }else{
	        			        	Ext.Msg.alert('系统提示', results.message);
	        			        }
	        			    }
	        			});
	    			}else{
	    				Ext.Msg.alert('系统提示', '请选择需要重置密码的账号!');
	    			}	        			
        		}
        	}]
        }]
    });
    

	var form = Ext.create('Ext.form.Panel', {
		width: 380,
		bodyPadding: 10,
        fieldDefaults: {
            labelAlign: 'right',
            labelWidth: 60,
            msgTarget: 'side'
        },
        layout: 'anchor',
        defaults: {
            anchor: '100%'
        },
		items : [{
			xtype:'hiddenfield',
			fieldLabel:'id',
			name:'id'
		},{
			xtype:'textfield',
			fieldLabel:'用户名',
			name:'login_name',
			allowBlank: false
		},{
			xtype:'textfield',
			fieldLabel:'密码',
			name:'login_pwd',
			inputType : 'password',
			allowBlank: false
		},{
			xtype:'combobox',
			fieldLabel:'权限角色',
			name:'role__id',
			editable:false,
			multiSelect: false,
			valueField:'id',
			displayField:'text',
			queryMode:'local',
			allowBlank: false,
		    store: new Ext.data.Store({ 
		        singleton : false, 
			   	proxy: {
			   		type: 'ajax',
			   	    url: '/usercontrol/sysrole_list/',
			   	    actionMethods:'post',
			   	    reader: {
			   			type: 'json'
			   	    }
			   	},
		        fields:['id', 'text'], 
		    	autoLoad:true 
		    })
		},{
			xtype:'combobox',
			name:'employe__id',
			fieldLabel: '关联员工', 
			allowBlank: false,
			typeAhead:true,
			editable:false,
        	minChars:1,
        	editable:true,
			store: new Ext.data.Store({ 
			    singleton : true, 
			   	   proxy: {
			   	        type: 'ajax',
						url: '/employecontrol/employe_select/',
						actionMethods:'post',
						reader: {
			    			type: 'json'
			        	}
			    	},
			 	fields:['id', 'name'],
			 	autoLoad:true 
			 }), 
			 loadingText:'正在加载数据，请稍侯……', 
			 triggerAction:'all', 
			 valueField:'id', 
			 displayField:'name',
			 listeners: {
	    		'select': function(combo, records, opts) {	
	   	    		//alert("待增加学生查找") ;
	    		},
	    		'beforequery' : function(queryEvent,eOpts){
					queryEvent.combo.getStore().load();
				} 
	
	    	}
		},{
			xtype:'textfield',
			fieldLabel:'MAC地址',
			name:'mac'
		},{
			xtype:'textfield',
			fieldLabel:'IP地址',
			regex:/^(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])$/ ,
			name:'ip'
		},{
			xtype:'checkboxfield',
			fieldLabel:'是否激活',
			inputValue:'1',
			name:'login_state'
		}]
	});
	
	var win = Ext.create('Ext.window.Window', {
		//title : '---',
		modal: true,
		closeAction: 'hide',
		items : [form],
		plain : true,
		resizable : false,
		buttonAlign : 'center',
		buttons : [ {
			text : '保存',
			handler : function() {
				if (form.getForm().isValid()) {
					form.getForm().submit({
						waitTitle : '请稍候',
						waitMsg : '正在处理......',
						url : '/usercontrol/sysuser_save/',
						success : function(form, action) {
							win.hide();
							SysUserStore.load();
						},
						failure : function(form, action) {
							if (action.result) {
								Ext.Msg.alert('系统提示', action.result.message);
							} 
						}
					});
				}
			}
		}, {
			text : '取消',
			handler : function() {
				form.getForm().reset();
				win.hide();
			}
		}]
	}); 
	
	Ext.create('Ext.container.Viewport',{
		layout:'fit',
		renderTo: 'sysuser-grid',
		items:[SysUserGrid]
	});
});